/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.pay.service.impl;

import me.zhengjie.exception.EntityExistException;
import me.zhengjie.pay.domain.JjzhWxPayOrders;
import me.zhengjie.pay.repository.JjzhWxPayOrdersRepository;
import me.zhengjie.pay.service.JjzhWxPayOrdersService;
import me.zhengjie.pay.service.dto.JjzhWxPayOrdersDto;
import me.zhengjie.pay.service.dto.JjzhWxPayOrdersQueryCriteria;
import me.zhengjie.pay.service.mapstruct.JjzhWxPayOrdersMapper;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xxx
* @date 2025-03-28
**/
@Service
@RequiredArgsConstructor
public class JjzhWxPayOrdersServiceImpl implements JjzhWxPayOrdersService {

    private final JjzhWxPayOrdersRepository jjzhWxPayOrdersRepository;
    private final JjzhWxPayOrdersMapper jjzhWxPayOrdersMapper;

    @Override
    public Map<String,Object> queryAll(JjzhWxPayOrdersQueryCriteria criteria, Pageable pageable){
        Page<JjzhWxPayOrders> page = jjzhWxPayOrdersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(jjzhWxPayOrdersMapper::toDto));
    }

//    @Override
//    public Map<String, Object> queryAll(JjzhWxPayOrdersQueryCriteria criteria, Pageable pageable) {
//        // 如果传递了payTime，转换为当天的起始和结束时间
//        if (criteria.getPayTime() != null) {
//            // 将 Instant 转换为 LocalDate
//            LocalDate date = criteria.getPayTime().atZone(ZoneOffset.UTC).toLocalDate();
//
//            // 计算当天的开始时间（00:00:00）
//            Instant startOfDay = date.atStartOfDay(ZoneOffset.UTC).toInstant();
//            // 计算当天的结束时间（23:59:59）
//            Instant endOfDay = date.plusDays(1).atStartOfDay(ZoneOffset.UTC).minusMillis(1).toInstant();
//
//            // 设置条件
//            criteria.setPayTime(startOfDay);  // 这里只设置起始时间
//            // 你可以在 QueryHelp 中扩展查询，增加结束时间条件，或者在此手动处理
//        }
//
//        // 查询数据
//        Page<JjzhWxPayOrders> page = jjzhWxPayOrdersRepository.findAll(
//                (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder),
//                pageable
//        );
//        return PageUtil.toPage(page.map(jjzhWxPayOrdersMapper::toDto));
//    }


    @Override
    public List<JjzhWxPayOrdersDto> queryAll(JjzhWxPayOrdersQueryCriteria criteria){
        return jjzhWxPayOrdersMapper.toDto(jjzhWxPayOrdersRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public JjzhWxPayOrdersDto findById(String wxPayOrdersId) {
        JjzhWxPayOrders jjzhWxPayOrders = jjzhWxPayOrdersRepository.findById(wxPayOrdersId).orElseGet(JjzhWxPayOrders::new);
        ValidationUtil.isNull(jjzhWxPayOrders.getWxPayOrdersId(),"JjzhWxPayOrders","wxPayOrdersId",wxPayOrdersId);
        return jjzhWxPayOrdersMapper.toDto(jjzhWxPayOrders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JjzhWxPayOrdersDto create(JjzhWxPayOrders resources) {
        resources.setWxPayOrdersId(IdUtil.simpleUUID());
        if(jjzhWxPayOrdersRepository.findByOrderNo(resources.getOrderNo()) != null){
            throw new EntityExistException(JjzhWxPayOrders.class,"ORDER_NO",resources.getOrderNo());
        }
        return jjzhWxPayOrdersMapper.toDto(jjzhWxPayOrdersRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(JjzhWxPayOrders resources) {
        JjzhWxPayOrders jjzhWxPayOrders = jjzhWxPayOrdersRepository.findById(resources.getWxPayOrdersId()).orElseGet(JjzhWxPayOrders::new);
        jjzhWxPayOrders.copy(resources);
        jjzhWxPayOrdersRepository.save(jjzhWxPayOrders);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String wxPayOrdersId : ids) {
            jjzhWxPayOrdersRepository.deleteById(wxPayOrdersId);
        }
    }

    @Override
    public void download(List<JjzhWxPayOrdersDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (JjzhWxPayOrdersDto jjzhWxPayOrders : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("居家照护申请ID", jjzhWxPayOrders.getBisZhsqId());
            map.put("子商户号", jjzhWxPayOrders.getSubMchind());
            map.put("商户订单号", jjzhWxPayOrders.getOrderNo());
            map.put("商户订单号", jjzhWxPayOrders.getOrderNo());
            map.put("支付金额（单位：分）", jjzhWxPayOrders.getAmount());
            map.put("姓名", jjzhWxPayOrders.getBisZhsqSnryXm());
            map.put("身份证", jjzhWxPayOrders.getBisZhsqSnrySfz());
            map.put("币种（默认人民币）", jjzhWxPayOrders.getCurrency());
            map.put("订单状态: 0下单成功,1支付成功,2退款", jjzhWxPayOrders.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public JjzhWxPayOrders findByOrderNo(String outTradeNo) {
        JjzhWxPayOrders jjzhWxPayOrders = jjzhWxPayOrdersRepository.findByOrderNo(outTradeNo);
        return jjzhWxPayOrders;
    }
}
